<?php

// +----------------------------------------------------------------------
// |Author: 翼小菜
// +----------------------------------------------------------------------
// |Description: 部门|角色成员管理API
// +----------------------------------------------------------------------
// |更多功能可联系QQ314688769
// +----------------------------------------------------------------------
namespace api\cveadmin\controller;
use cmf\controller\RestAdminBaseController;
use app\admin\logic\UserLogic;
use api\cveadmin\model\UserModel;
use api\cveadmin\model\UserTokenModel;
use api\cveadmin\service\UserService;
use api\cveadmin\model\RoleUserModel;
class AdminUserController extends RestAdminBaseController
{
    /**
     * 获取管理成员
     * @throws \think\exception\DbException
     * @OA\Get(
     *     tags={"cveadmin"},
     *     path="/cveadmin/admin_users/{id}/get/users",
     *     summary="根据部门获取成员",
     *     description="部门成员-获取成员",
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         description="角色id|部门id",
     *         required=true,
     *         @OA\Schema(
     *             type="integer",
     *         )
     *     ),
     *     @OA\Response(response=200,ref="#/components/responses/200")
     * )
     */
    public function getUsers()
    {
        //角色ID
        $roleId = $this->request->param("id", 0, 'intval');
        if (empty($roleId)) {
            $this->error("参数错误！");
        }
        $userService = new UserService;
        $users = $userService->getAdminUsersByRoleId($roleId);
        $this->success('success',$users);
    }
    /**
     * 添加管理员
     * @throws \think\exception\DbException
     * @OA\Post(
     *     tags={"cveadmin"},
     *     path="/cveadmin/admin_users",
     *     summary="添加管理员",
     *     description="添加管理员",
     *     @OA\RequestBody(
     *         description="请求参数",
     *         @OA\MediaType(
     *             mediaType="application/x-www-form-urlencoded",
     *             @OA\Schema(ref="#/components/schemas/AdminUserSaveRequestForm")
     *         ),
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(ref="#/components/schemas/AdminUserSaveRequest")
     *         )
     *     ),
     *     @OA\Response(
     *          response="1",
     *          description="success",
     *          @OA\JsonContent(example={"code": 1,"msg": "success","data":{
     *              "item":{"id": 1,"status": 1,"delete_time": 0,"name": "又菜又爱玩","remark": ""}
     *          }})
     *     ),
     *     @OA\Response(
     *          response="0",
     *          @OA\JsonContent(example={"code": 0,"msg": "error!","data":""})
     *     ),
     * )
     */
    public function save()
    {
        // $param = $this->request->param();
        // file_put_contents("success1.txt",json_encode($param).'--2--'.date('H:i:s')."\n", FILE_APPEND);
        // die;
        if ($this->request->isPost()) {
            $roleIds = $this->request->param('role_ids/a');
           
            if (!empty($roleIds) && is_array($roleIds)) {
                $data   = $this->request->param();
                $result = $this->validate($data, 'User.add');
                if ($result !== true) {
                    $this->error($result);
                } else {
                    $data['user_pass']       = cmf_password($data['user_pass']);
                    $data['create_time']     = time();
                    $data['last_login_time'] = $data['create_time'];
                    $user                    = UserModel::create($data);
                    if (!empty($user['id'])) {
                        foreach ($roleIds as $roleId) {
                            if ($this->getUserId() != 1 && $roleId == 1) {
                                $this->error("为了网站的安全，非网站创建者不可创建超级管理员！");
                            }
                            RoleUserModel::insert(["role_id" => $roleId, "user_id" => $user['id']]);
                        }
                        $this->success(lang('ADD_SUCCESS'), ['item' => $user]);
                    } else {
                        $this->error(lang('ADD_FAILED'));
                    }
                }
            } else {
                $this->error("请为此用户指定角色！");
            }

        }
    }

    /**
     * 编辑管理员
     * @throws \think\exception\DbException
     * @OA\Put(
     *     tags={"cveadmin"},
     *     path="/cveadmin/admin_users/{id}",
     *     summary="编辑管理员",
     *     description="编辑管理员",
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         description="管理员id",
     *         required=true,
     *         @OA\Schema(
     *             type="integer",
     *         )
     *     ),
     *     @OA\RequestBody(
     *         description="请求参数",
     *         @OA\MediaType(
     *             mediaType="application/x-www-form-urlencoded",
     *             @OA\Schema(ref="#/components/schemas/AdminUserSaveRequestForm")
     *         ),
     *         @OA\MediaType(
     *             mediaType="application/json",
     *             @OA\Schema(ref="#/components/schemas/AdminUserSaveRequest")
     *         )
     *     ),
     *     @OA\Response(
     *          response="1",
     *          description="success",
     *          @OA\JsonContent(example={"code": 1,"msg": "保存成功","data":""})
     *     ),
     *     @OA\Response(
     *          response="0",
     *          @OA\JsonContent(example={"code": 0,"msg": "error!","data":""})
     *     ),
     * )
     */
    public function update($id)
    {
        $roleIds = $this->request->param('role_ids/a');
        if (!empty($roleIds) && is_array($roleIds)) {
            $data = $this->request->param();
            if (empty($data['user_pass'])) {
                unset($data['user_pass']);
            } else {
                $data['user_pass'] = cmf_password($data['user_pass']);
            }
            $result = $this->validate($data, 'User.edit');

            if ($result !== true) {
                // 验证失败 输出错误信息
                $this->error($result);
            } else {
                $currentUserId = $this->getUserId();
                $userId        = $this->request->param('id', 0, 'intval');
                $result        = UserModel::strict(false)->where('id', $userId)->save($data);
                if ($result !== false) {
                    RoleUserModel::where("user_id", $userId)->delete();
                    foreach ($roleIds as $roleId) {
                        if ($currentUserId != 1 && $roleId == 1) {
                            $this->error("为了网站的安全，非网站创建者不可创建超级管理员！");
                        }
                        RoleUserModel::insert(["role_id" => $roleId, "user_id" => $userId]);
                    }
                    $this->success(lang('EDIT_SUCCESS'));
                } else {
                    $this->error(lang('EDIT_FAILED'));
                }
            }
        } else {
            $this->error("请为此用户指定角色！");
        }
    }

    /**
     * 删除管理员
     * @throws \think\exception\DbException
     * @OA\Delete(
     *     tags={"cveadmin"},
     *     path="/cveadmin/admin_users/{id}",
     *     summary="删除管理员",
     *     description="删除管理员",
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         description="管理员id",
     *         required=true,
     *         @OA\Schema(
     *             type="integer",
     *         )
     *     ),
     *     @OA\Response(
     *          response="1",
     *          description="success",
     *          @OA\JsonContent(example={"code": 1,"msg": "删除成功!","data":""})
     *     ),
     *     @OA\Response(
     *          response="0",
     *          @OA\JsonContent(example={"code": 0,"msg": "error","data":""})
     *     ),
     * )
     */
    public function delete($id)
    {
        $id = $this->request->param('id', 0, 'intval');
        if (!UserLogic::isCreator($this->getUserId())) {
            $this->error('为了网站的安全，非网站创建者不可删除');
        }
        if ($id == 1) {
            $this->error("最高管理员不能删除！");
        }

        if (UserModel::destroy($id) !== false) {
            RoleUserModel::where('user_id', $id)->delete();
            $this->success(lang('DELETE_SUCCESS'));
        } else {
            $this->error(lang('DELETE_FAILED'));
        }
    }
    /**
     * 设置管理员启用状态
     * @throws \think\exception\DbException
     * @OA\Put(
     *     tags={"cveadmin"},
     *     path="/cveadmin/admin_user/{id}/status/{status}",
     *     summary="设置管理员启用状态",
     *     description="设置管理员启用状态",
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         description="管理员id",
     *         required=true,
     *         @OA\Schema(
     *             type="integer",
     *         )
     *     ),
     *     @OA\Parameter(
     *         name="status",
     *         in="path",
     *         description="状态,0:禁用;1:启用",
     *         example="1",
     *         required=true,
     *         @OA\Schema(
     *             type="integer",
     *         )
     *     ),
     *     @OA\Response(
     *          response="1",
     *          description="success",
     *          @OA\JsonContent(example={"code": 1,"msg": "操作成功!","data":""})
     *     ),
     *     @OA\Response(
     *          response="0",
     *          @OA\JsonContent(example={"code": 0,"msg": "数据传入失败！","data":""})
     *     ),
     * )
     */
    public function status()
    {
        $id     = $this->request->param('id', 0, 'intval');
        $status = $this->request->param('status', 0, 'intval');
        if (!empty($id)) {
            if (!UserLogic::isCreator($this->getUserId())) {
                $this->error('为了网站的安全,非网站创建者【admin】其余用户不可更改成员状态');
            }
            $status = empty($status) ? 0 : 1;
            UserModel::where(['id' => $id])->update(['user_status' => $status]);
            // 拉黑成功后清理其token,让其自动下线
            UserTokenModel::where('user_id',$id)->update(['token' => '']);
            $this->success('操作成功！');
        } else {
            $this->error('数据传入失败！');
        }
    }
}
